22. Exercise: Topic Notifications

L1 A22 Sending FCM Notifications To A Topic

Useful Links

Exercise

  1. Open EggTimerFragment.kt and find TODO 3.3. Create a function named subscribe.to topic. You need get an instance of FirebaseMessaging and call subscibeToTopic() function with the topic name. You also need to add an addOnCompleteListener to get notified back from FCM on if your subscription is succeeded or failed.
// EggTimerFragment.kt

   // TODO: Step 3.3 subscribe to breakfast topic
    private fun subscribeTopic() {
        // [START subscribe_topics]
        FirebaseMessaging.getInstance().subscribeToTopic(TOPIC)
            .addOnCompleteListener { task ->
                var msg = getString(R.string.message_subscribed)
                if (!task.isSuccessful) {
                    msg = getString(R.string.message_subscribe_failed)
                }
                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
            }
        // [END subscribe_topics]
    }
  1. You need to call this function to subscribe to a topic when the app starts. To do that, scroll up to onCreateView()and add a call to subscribeTopic().
// EggTimerFragment.kt

   // TODO: Step 3.4 call subscribe topics on start
    subscribeTopic()
    return binding.root
  1. To subscribe to the breakfast topic, run the app again. You should see a toast message saying “Subscribed to topic”



  2. Now you can test sending messages to a topic but before that let's run this on another emulator instance too so we can test with multiple devices.



  3. Open the Notifications composer and select New Notification.



  4. Set the notification Title and Text as before. This time instead of sending the message to a single device, click Topic under **Target **and enter ‘breakfast’ as the topic name.



  1. Make sure your app is in the background. Next click Review and click Publish. You should see the notification is received on all devices that subscribed to this topic.

The app has more than one channel for notifications now. If you long click the app icon, select info and click notifications, you should see more than one notification channels. If you deselect the breakfast channel, your app will not receive any notifications sent over this channel. You can test this with notification composer but don’t forget to turn on notifications for this channel once you are done testing.

When using notifications, always keep in mind that users can turn off any notification channel at any time.